<template>
  <div class="wh100 addbox flexbox flexbox_column">
    <div class="flexbox">
      <div class="flexCenter">
        <el-button type="success" size="default" style="width: 100px;height: 36px;" @click="returnHandler"
          >返回</el-button
        >
      </div>

      <div class="wh100 flexbox flex_center">
        <h2 style="font-size:20px;">
          {{ infoModel.isAdd == 'add' ? '新增订单' : `${infoModel.warehouse_code || ''} --- 修改` }}
        </h2>
      </div>
    </div>

    <div class="infoBox flexbox_column mtop10">
      <el-form :model="infoModel" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-card class="flexbox_column">
          <div class="flexbox_row">
            <div class="leftbox flexbox_column">
              <h3 class="flexbox">物流信息</h3>

              <el-row class="flexbox flexbox_column">
                <el-col :span="24" class="flexbox">
                  <el-form-item label="仓库：" class="mb0" prop="code">
                    <el-select v-model="infoModel.code" clearable class="w350px" placeholder="请选择">
                      <el-option
                        v-for="ele in warehouseList"
                        :key="ele.code"
                        :label="ele.name"
                        :value="ele.code"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="创建类型：" class="mb0" prop="create_type">
                    <el-select v-model="infoModel.create_type" clearable class="w350px" placeholder="请选择">
                      <!-- 1：手动创建   2：平台推 -->
                      <el-option label="手动创建" value="1"></el-option>
                      <el-option label="平台推" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="订单类型：" class="mb0" prop="order_type">
                    <el-select v-model="infoModel.order_type" clearable class="w350px" placeholder="请选择">
                      <!-- 1:一件代发发的订单，2:转运的订-->
                      <el-option label="一件代发发的订单" value="1"></el-option>
                      <el-option label="转运的订单" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24" class="flexbox">
                  <el-form-item label="运输方式：" class="mb0" prop="ship_type">
                    <el-select v-model="infoModel.ship_type" clearable class="w350px" placeholder="请选择">
                      <!-- 0:公路运输,1:铁路运输,2:水路运输,3:航空运输,4:管道运输 -->
                      <el-option label="公路运输" value="0"></el-option>
                      <el-option label="铁路运输" value="1"></el-option>
                      <el-option label="水路运输" value="2"></el-option>
                      <el-option label="航空运输" value="3"></el-option>
                      <el-option label="管道运输" value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="币种：" class="mb0" prop="money_type">
                    <el-select v-model="infoModel.money_type" clearable class="w350px" placeholder="请选择">
                      <!-- 0:人民币，1：美元，2：欧元，3：英镑，4:日元) -->
                      <el-option label="人民币" value="0"></el-option>
                      <el-option label="美元" value="1"></el-option>
                      <el-option label="欧元" value="2"></el-option>
                      <el-option label="英镑" value="3"></el-option>
                      <el-option label="日元" value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="订单总价：" class="mb0" prop="total_price">
                    <el-input-number
                      v-model="infoModel.total_price"
                      :max="99999999"
                      :min="0"
                      :controls="false"
                      class="inlineBlock w350px"
                      placeholder="number"
                    ></el-input-number>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="承运商：" class="mb0" prop="logistics">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.logistics"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="跟踪号：" class="mb0" prop="trackingNo">
                    <el-input
                      type="textarea"
                      placeholder="请输入"
                      maxlength="500"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.trackingNo"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="参考号：" class="mb0" prop="referenceNo">
                    <el-input
                      type="textarea"
                      placeholder="请输入"
                      maxlength="500"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.referenceNo"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="24" class="flexbox">
                  <el-form-item label="描述：" class="mb0">
                    <el-input
                      type="textarea"
                      placeholder="请输入"
                      maxlength="500"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.remake"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <div class="rightbox flex1">
              <h3 class="flexbox">收件人信息</h3>

              <el-row>
                <el-col :span="12" class="flexbox">
                  <el-form-item label="收件人：" class="mb0" prop="receiver">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.receiver"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="电子邮箱" prop="email" class="mb0">
                    <el-autocomplete
                      v-model="infoModel.email"
                      class="w350px"
                      :fetch-suggestions="querySearchEmail"
                      :trigger-on-focus="false"
                      placeholder="邮箱"
                    >
                    </el-autocomplete>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="国家：" class="mb0" prop="country">
                    <el-select
                      v-model="infoModel.country"
                      clearable
                      class="w350px"
                      @change="changeCountry($event, 'Province')"
                      placeholder="请选择"
                    >
                      <el-option v-for="ele in CountryList" :key="ele.id" :label="ele.cname" :value="ele.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="公司名称：" class="mb0" prop="companyName">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.companyName"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="省/州：" class="mb0" prop="city_code">
                    <el-select
                      v-model="infoModel.city_code"
                      clearable
                      :disabled="!infoModel.country"
                      class="w350px"
                      @change="changeCountry($event, 'city')"
                      placeholder="请选择"
                    >
                      <el-option v-for="ele in ProvinceList" :key="ele.id" :label="ele.cname" :value="ele.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="联系电话：" class="mb0" prop="phone">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.phone"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="城市/区：" class="mb0" prop="area_code">
                    <el-select
                      v-model="infoModel.area_code"
                      clearable
                      :disabled="!infoModel.city_code"
                      class="w350px"
                      placeholder="请选择"
                    >
                      <el-option v-for="ele in cityList" :key="ele.id" :label="ele.cname" :value="ele.id"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="邮编：" class="mb0" prop="post_code">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      class="w350px"
                      show-word-limit
                      v-model.trim="infoModel.post_code"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="收件地区：" class="mb0" prop="address">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.address"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="门牌号：" class="mb0" prop="detail">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.detail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12" class="flexbox">
                  <el-form-item label="收件地区1：" class="mb0">
                    <el-input
                      placeholder="请输入"
                      maxlength="100"
                      show-word-limit
                      class="w350px"
                      v-model.trim="infoModel.address_another"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <div class="table mtop10">
            <h3 class="flexbox">发货产品</h3>

            <el-table :data="infoModel.products" highlight-current-row border class="wh100">
              <el-table-column prop="tracking_number" header-align="center" align="center" label="SKU">
                <template slot-scope="scope">
                  <div class="boxposition">
                    <el-select
                      v-model="infoModel.products[scope.$index].sku"
                      clearable
                      @change="changeSkuHandler($event, scope.$index)"
                      style="min-width:150px;max-width:250px;"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="ele in regionList"
                        :key="ele.id"
                        :label="ele.sku"
                        :disabled="skuHandlerDisabled(ele.sku)"
                        :value="ele.sku"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="tracking_number" header-align="center" align="center" label="产品名称">
                <template slot-scope="scope">
                  <div class="boxposition">
                    {{ infoModel.products[scope.$index].name }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="length" header-align="center" align="center" label="尺寸&重量">
                <template slot-scope="scope">
                  {{ sizeOfWeight(infoModel.products[scope.$index]) }}
                </template>
              </el-table-column>

              <el-table-column prop="length" header-align="center" align="center" label="可用库存">
                <template slot-scope="scope">
                  {{ infoModel.products[scope.$index].stock }}
                </template>
              </el-table-column>

              <el-table-column prop="tracking_number" header-align="center" align="center" label="发货数量">
                <template slot-scope="scope">
                  <div class="boxposition">
                    <el-input-number
                      v-model="infoModel.products[scope.$index].num"
                      :max="999999"
                      :min="0"
                      :controls="false"
                      class="inlineBlock"
                      placeholder="number"
                      style="width:130px;"
                    ></el-input-number>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="120" align="center" fixed="right">
                <template #default="scope">
                  <el-button type="danger" icon="el-icon-delete" @click="changeDelete('delete', scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <el-button
              type="success"
              icon="el-icon-add"
              style="margin-right: 20px;"
              class="mtop10"
              :disabled="infoModel.products.length >= regionList.length"
              @click="changeAdd"
              >添加产品</el-button
            >
          </div>

          <div class="foot mtop10 flexCenter">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" class="mleft50" :loading="loading" @click="submitForm">提交</el-button>
          </div>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script>
import { vaildatorRules } from './rule'
import API from '@/api/warehousing.js'
import APIOrder from '@/api/order.js'
import APICommon from '@/api/common.js'
import { getInitTime } from '@/libs/common.js'

export default {
  name: 'OrderAdd',
  props: {
    infoModel: {
      type: Object,
      default: () => ({}),
    },
    showModel: {
      type: Boolean,
      default: () => false,
    },

    warehouseList: {
      type: Array,
      default: () => [],
    },
  },

  watch: {
    showModel: {
      handler(val) {
        if (val) {
          if (!this.regionList.length) {
            this.getProductTypeHandler()
          }

          if (!this.CountryList.length) {
            this.getCountryListHandler()
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },

  data() {
    return {
      loading: false,
      regionList: [],
      CountryList: [],
      ProvinceList: [],
      cityList: [],
      rules: vaildatorRules(this),
    }
  },

  computed: {
    sizeOfWeight() {
      return row => {
        const { length = '', width = '', height = '', lwh_type = '', weight = '', weight_type = '' } = row
        let unit = ''
        if (lwh_type == 1) {
          unit = 'cm'
        } else if (lwh_type == 2) {
          unit = 'in'
        }

        let mass = ''
        if (weight_type == 1) {
          mass = 'kg'
        } else if (weight_type == 2) {
          mass = 'lb/oz'
        }

        if (!length && !width && !height && !unit && !weight && !mass) {
          return ''
        }
        const val = `${length}*${width}*${height} ${unit} & ${weight} ${mass}`
        return val == '**  &   ' ? '' : val
      }
    },

    skuHandlerDisabled() {
      return sku => {
        if (!sku) return false

        const list = this.infoModel.products
        const flag = list.filter(e => sku === e.sku)
        return !!flag.length
      }
    },
  },

  methods: {
    changeSkuHandler(e, idex) {
      this.regionList.forEach(item => {
        if (e == item.sku) {
          const {
            name,
            id,
            sku,
            length = '',
            width = '',
            height = '',
            lwh_type = '',
            weight = '',
            weight_type = '',
          } = item
          this.infoModel.products[idex] = { name, id, sku, length, width, height, lwh_type, weight, weight_type }
          this.$forceUpdate()
          console.log(this.infoModel.products)
        }
      })
    },
    /**
     * 产品
     */
    async getProductTypeHandler() {
      try {
        const RES = await API.getProductHanlder()
        console.log(RES, '产品品类')
        this.regionList = RES.data || []
      } catch (error) {
        console.log(error)
      }
    },

    changeCountry(e, type) {
      console.log(e, type, 'type')
      if (type == 'Province') {
        this.ProvinceList = []
        this.cityList = []
        if (e) {
          this.getProvinceHandler(e)
        }
      } else if (type == 'city') {
        this.cityList = []
        if (e) {
          this.getCityListHandler(e)
        }
      }
    },
    /**
     * 国家
     */
    async getCountryListHandler() {
      try {
        const RES = await APICommon.getCountryList()
        // console.log(RES, '国家')
        this.CountryList = RES || []
      } catch (error) {
        console.log(error)
      }
    },

    /**
     * 省
     */
    async getProvinceHandler(id) {
      try {
        const RES = await APICommon.getProvinceList(id)
        console.log(RES, '省')
        this.ProvinceList = RES || []
        this.infoModel.city_code = ''
        this.infoModel.area_code = ''
        this.$set(this.infoModel, 'city_code', '')
        this.$set(this.infoModel, 'area_code', '')
      } catch (error) {
        console.log(error)
      }
    },

    /**
     * 市
     */
    async getCityListHandler(id) {
      try {
        const RES = await APICommon.getCityList(id)
        console.log(RES, '市')
        this.cityList = RES || []
        this.infoModel.area_code = ''
        this.$set(this.infoModel, 'area_code', '')
      } catch (error) {
        console.log(error)
      }
    },
    querySearchEmail(queryString, callback) {
      const emailList = [
        { value: '@qq.com' },
        { value: '@126.com' },
        { value: '@163.com' },
        { value: '@sina.com' },
        { value: '@21cn.com' },
        { value: '@sohu.com' },
        { value: '@yahoo.com.cn' },
        { value: '@tom.com' },
        { value: '@etang.com' },
        { value: '@eyou.com' },
        { value: '@56.com' },
        { value: '@x.cn' },
        { value: '@chinaren.comsogou.com' },
        { value: '@citiz.com' },
      ]
      let results = []
      const queryList = []
      emailList.forEach(item => {
        queryList.push({ value: queryString.split('@')[0] + item.value })
      })
      results = queryString ? queryList.filter(this.createFilter(queryString)) : queryList
      callback(results)
    },

    // 邮箱填写过滤
    createFilter(queryString) {
      return item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    },

    changeDelete(row) {
      this.infoModel.inbound_packages_list.splice(row.$index, 1)
    },

    changeAdd() {
      this.infoModel.products.push({ sku: '', name: '' })
    },

    submitForm() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          try {
            this.loading = true

            let res = null
            const params = { ...this.infoModel }

            if (params.estimate_delivery_time) {
              params.estimate_delivery_time = getInitTime(params.estimate_delivery_time, 'YYYY-MM-DD')
            }

            params.products = params.products.map(item => ({ sku: item.sku, num: item.num }))

            if (params.isAdd == 'add') {
              res = await APIOrder.addOrderHandler(params)
            } else {
              res = await APIOrder.editOrder(params)
            }

            this.loading = false

            if ((params.isAdd == 'add' && res.code == 1) || (params.isAdd == 'edit' && res.code == 2)) {
              this.$message({
                message: '提交成功',
                type: 'scuccess',
              })
              this.resetForm()
            } else {
              this.$message({
                message: `提交失败：${res.message}`,
                type: 'warning',
              })
            }
          } catch (error) {
            console.error(error)
            this.loading = false
            this.$message({
              message: `网络异常/提交失败：${error}`,
              type: 'warning',
            })
          }
        }
      })
    },

    resetForm() {
      this.$refs.ruleForm.resetFields()
      this.returnHandler()
    },
    returnHandler() {
      this.$emit('close', 'close')
    },
  },
}
</script>

<style lang="scss" scoped>
.leftbox {
  width: 550px;
  padding: 20px 16px;
  border-radius: 8px;
  background-color: #e9eef3;
  border: 1px solid #d4cfcf;
}

.rightbox {
  min-height: 400px;
  border: 1px solid #d4cfcf;
  border-radius: 8px;
  background-color: #e9eef3;
  margin-left: 10px;
  padding: 20px 16px;
}

.table {
  min-height: 400px;
  border: 1px solid #d4cfcf;
  border-radius: 8px;
  background-color: #e9eef3;
  margin-left: 10px;
  padding: 20px 16px;
}
.foot {
  width: 100%;
  border-radius: 8px;
  height: 70px;
  border: 1px solid #d4cfcf;
  background-color: #e9eef3;
}
</style>
